package com.chenfan.ccp.util;

import org.apache.commons.io.IOUtils;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @className: 文件处理工具类
 * @description: 日期处理类
 * @author: Leo
 * @date: 2020/12/27 8:11 上午
 **/
public class FileUtil {
    public static String suffix(String fileName){
        if(null == fileName || "".equals(fileName)) {
            return "";
        }
        if(!fileName.contains(".")) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf(".")+1);
    }

    public static void downloadWithZip(String zipName, List<FilePackage> fileStream,
                                       HttpServletRequest request, HttpServletResponse response) throws IOException {

        zipName = dealZipNameByUserAgent(zipName, request);
        // 初始化信息
        response.setContentType("application/zip");
        response.setHeader("Content-disposition", "attachment; filename=" + zipName);
        ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
        // 获取文件信息
        Set<String> fileSet = new HashSet<>();
        for (int i = 0; i < fileStream.size(); i++) {
            FilePackage filePackage = fileStream.get(i);
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            IOUtils.copy(filePackage.getInputStream(), byteOut);
            String orignalName = filePackage.getFileName();
            if (fileSet.contains(orignalName)) {
                int index = orignalName.lastIndexOf(".");
                String fileName = orignalName.substring(index - 1);
                String suffix = orignalName.substring(index);
                orignalName = fileName + System.currentTimeMillis() + suffix;
            }
            fileSet.add(orignalName);
            zipOut.putNextEntry(new ZipEntry(orignalName));
            zipOut.write(byteOut.toByteArray());
            zipOut.closeEntry();
            byteOut.close();
        }
        zipOut.flush();
        zipOut.close();
    }

    private static String dealZipNameByUserAgent(String zipName, HttpServletRequest request) throws UnsupportedEncodingException {
        // 转换文件名，防止乱码
        zipName = new String(zipName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
        // 获得请求头中的User-Agent
        String agent = request.getHeader("User-Agent");
        // 根据不同的客户端进行不同的编码
        if (agent.contains("MSIE")) {
            // IE浏览器
            zipName = URLEncoder.encode(zipName, "utf-8");
            zipName = zipName.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            BASE64Encoder base64Encoder = new BASE64Encoder();
            zipName = "=?utf-8?B?" + base64Encoder.encode(zipName.getBytes(StandardCharsets.UTF_8)) + "?=";
        } else {
            // 其它浏览器
            zipName = URLEncoder.encode(zipName, "utf-8");
        }
        return zipName;
    }


    public static class FilePackage {

        private String fileName;

        private InputStream inputStream;

        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public InputStream getInputStream() {
            return inputStream;
        }

        public void setInputStream(InputStream inputStream) {
            this.inputStream = inputStream;
        }
    }


}
